package fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.menhoo.toollibrary.common.assist.Network;
import com.example.menhoo.toollibrary.common.helper.ExitAppUtil;
import com.example.menhoo.toollibrary.common.helper.MessageUtil;
import com.example.menhoo.toollibrary.common.io.FileUtils;
import com.example.menhoo.toollibrary.common.utils.BitmapUtil;
import com.example.menhoo.toollibrary.common.utils.HandlerUtil;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.BitmapGlobalConfig;
import com.lidroid.xutils.bitmap.callback.BitmapLoadCallBack;
import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom;
import com.lidroid.xutils.util.LogUtils;
import com.rey.material.widget.Switch;

import java.io.File;
import java.text.DecimalFormat;

import app.About;
import app.AllApp;
import app.ChangePassword;
import app.Main;
import app.MyDownload;
import app.UploadApp;
import app.im.details.IMDetailsActivity;
import application.AppApplication;
import application.KeyConstant;
import application.UIHttpURL;
import application.UIKeyValueSet;
import custom.BadgeView;
import custom.ScaleImagesActivity;
import interfaces.IReturnObject;
import mainUI.AppFragment;
import menhoo.com.i8officelibrary.R;
import model.ImageInfo;
import model.LoginUser;
import model.TabModel;
import service.DownLoadService;
import service.SignalrService;
import utils.PermissionUtils;

/**
 * Created by yanglei on 15/9/17.
 */
public class MY extends AppFragment {


    TextView textViewName;

    TextView textViewDeptAndPos;

    TextView textView_clear;

    ImageView imageViewUser;

    LinearLayout ripple_sort;

    LinearLayout ripple_down_list;

    LinearLayout ripple_change_pwd;

    LinearLayout ripple_check_new_versioin;

    LinearLayout ripple_only_wifi_upload_download;

    Switch switchWifi;
    Switch switchIsNotificationOpen;

    Switch switchIsDownloadTestApk;

    LinearLayout ripple_clear;

    LinearLayout ripple_exit;

    LinearLayout ripple_about;

    LoginUser user;

    BadgeView badgeViewNewVer;

    @Override
    public boolean onBackPressed() {
        return false;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContextView(R.layout.fragment_my);
    }

    @Override
    public void init() {
        super.init();

        //
        try {
            textViewName = (TextView) rootView.findViewById(R.id.textViewName);
            textViewDeptAndPos = (TextView) rootView.findViewById(R.id.textViewDeptAndPos);
            textView_clear = (TextView) rootView.findViewById(R.id.textView_clear);
            imageViewUser = (ImageView) rootView.findViewById(R.id.imageViewUser);
            ripple_sort = (LinearLayout) rootView.findViewById(R.id.ripple_sort);
            ripple_down_list = (LinearLayout) rootView.findViewById(R.id.ripple_down_list);
            ripple_change_pwd = (LinearLayout) rootView.findViewById(R.id.ripple_change_pwd);
            ripple_check_new_versioin = (LinearLayout) rootView.findViewById(R.id.ripple_check_new_versioin);
            switchIsNotificationOpen = (Switch) rootView.findViewById(R.id.switchIsNotificationOpen);
            ripple_only_wifi_upload_download = (LinearLayout) rootView.findViewById(R.id.ripple_only_wifi_upload_download);
            switchWifi = (Switch) rootView.findViewById(R.id.switchWifi);
            switchIsDownloadTestApk = (Switch) rootView.findViewById(R.id.switchIsDownloadTestApk);
            ripple_clear = (LinearLayout) rootView.findViewById(R.id.ripple_clear);
            ripple_exit = (LinearLayout) rootView.findViewById(R.id.ripple_exit);
            ripple_about = (LinearLayout) rootView.findViewById(R.id.ripple_about);
            //

            ripple_change_pwd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(context, ChangePassword.class));
                }
            });
            ripple_check_new_versioin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PermissionUtils.requestPermission(getActivity(), PermissionUtils.CODE_READ_EXTERNAL_STORAGE, mPermissionGrant);

                }
            });
            ripple_sort.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent it = new Intent(context, AllApp.class);
                    startActivity(it);
                }
            });
            imageViewUser.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent it = new Intent(getAppActivity(), ScaleImagesActivity.class);// 创建Intent对象
                    it.putExtra("imageInfo", new ImageInfo(user.EmplName, user.Image));
                    startActivity(it);
                    getActivity().overridePendingTransition(com.example.menhoo.menhoolibrary.R.anim.anim_scale_in, com.example.menhoo
                            .menhoolibrary.R
                            .anim.anim_scale_out);
                }
            });
            ripple_exit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    showSimpleDialogMessage("是否要退出登录?", new IReturnObject() {
                        @Override
                        public void returnResult(Object result) {
                            //向网站发送登出接口,解除阿里云推送
                            DeleteDeviceToken(AppApplication.getALiYunDeviceId(), new IReturnObject() {
                                @Override
                                public void returnResult(Object result) {

                                }
                            });


                        }
                    }, true, true);

                }
            });
            ripple_clear.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String dir_size = getCacheSize();
                    if (dir_size != null) {
                        BitmapGlobalConfig bitmapGlobalConfig = BitmapGlobalConfig.getInstance(context, AppApplication.getAppCachePath
                                (context));
                        bitmapGlobalConfig.clearMemoryCache();
                        bitmapGlobalConfig.clearCache();
                        MessageUtil.showShortToast(context, "清除了: " + dir_size + "MB 缓存数据");
                        textView_clear.setText("清除缓存");
                    } else {
                        MessageUtil.showShortToast(context, "缓存已经清空");
                    }
                }
            });
            ripple_down_list.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent it = new Intent(context, MyDownload.class);
                    startActivity(it);
                }
            });
            ripple_about.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent it = new Intent(context, About.class);
                    startActivity(it);
                }
            });


        } catch (Exception e) {
            LogUtils.e(e.getMessage() + "");
        }
        //
        badgeViewNewVer = new BadgeView(context, ripple_check_new_versioin);
        //
        user = AppApplication.getUser();
        textViewName.setText(user.EmplName);
        textViewDeptAndPos.setText(user.DeptAndPos);
        getBitmapLoader().display(imageViewUser, UIHttpURL.getWebSiteFullUrl(user.Image), new BitmapLoadCallBack<ImageView>() {
            @Override
            public void onLoadCompleted(ImageView imageView, String s, Bitmap bitmap, BitmapDisplayConfig bitmapDisplayConfig,
                                        BitmapLoadFrom bitmapLoadFrom) {
                imageView.setImageBitmap(BitmapUtil.getRoundedCornerBitmap(bitmap, 15f));
            }

            @Override
            public void onLoadFailed(ImageView imageView, String s, Drawable drawable) {
                imageView.setImageResource(R.mipmap.untitled);
            }
        });
        //
        switchWifi.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(Switch aSwitch, boolean b) {
                if (!Network.isWifi(context) && b) {
                    //不是wifi并且 b=true(打开仅用wifi上传),看看是否有下载任务如果有询问是否继续下载
                    DownLoadService downLoadService = getAppActivity().getDownLoadService();
                    if (downLoadService != null) {
                        downLoadService.stopAllDownloadTask(getDB());
                    }
                }
                AppApplication.getAppKeyValueSet().writeAppSetPreferences(UIKeyValueSet.IsOnlyWiFiUploadAndDownload, b + "");
            }
        });
        //
        switchWifi.setChecked(AppApplication.getAppKeyValueSet().readAppSetPreferences(UIKeyValueSet
                .IsOnlyWiFiUploadAndDownload).equalsIgnoreCase("true") ? true : false);
        switchIsNotificationOpen.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(Switch aSwitch, boolean b) {
                SharedPreferences sp = AppApplication.getInstance().getSharedPreferences("sp", Context.MODE_PRIVATE);
                sp.edit().putBoolean(UIKeyValueSet.IsNotificationOpen,!b).commit();
                AppApplication.getInstance().setNotification();
            }
        });
        //
        switchIsNotificationOpen.setChecked(!AppApplication.getInstance().getSharedPreferences("sp", Context.MODE_PRIVATE).getBoolean(UIKeyValueSet.IsNotificationOpen,true));
        //
        switchIsDownloadTestApk.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(Switch aSwitch, boolean b) {

                AppApplication.getAppKeyValueSet().writeAppSetPreferences(KeyConstant.IsDownloadUpdateTestApk, b + "");
            }
        });
        //
        switchIsDownloadTestApk.setChecked(AppApplication.getAppKeyValueSet().readAppSetPreferences(
                KeyConstant.IsDownloadUpdateTestApk).equalsIgnoreCase("true") ? true : false);

        //
        try {
            setNewVerTipShow(Main.isShowNewVerTip);
        } catch (Exception e) {
            LogUtils.e(e.getMessage() + "");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        String dir_size = getCacheSize();
        textView_clear.setText("清除缓存  " + (dir_size == null ? "" : dir_size + "MB"));
    }


    /**
     * 得到cache文件夹大小
     *
     * @return
     */
    String getCacheSize() {
        try {
            DecimalFormat df = new DecimalFormat("#0.00");

            float size = FileUtils.sizeOf(new File(AppApplication.getAppCachePath(context))) / 1024F / 1024F;
            String dir_size = df.format(size);

            if (!dir_size.equalsIgnoreCase("0.00")) {
                return dir_size;
            }
        } catch (Exception e) {
            LogUtils.e(e.getMessage() + "");
        }

        return null;
    }

    /*
    显示新版本提示
     */
    public void setNewVerTipShow(boolean F) {
        if (badgeViewNewVer != null) {
            if (F) {

                badgeViewNewVer.setBackgroundResource(R.drawable.corners_red_50dp);
                badgeViewNewVer.setText("新版本");
                badgeViewNewVer.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
                badgeViewNewVer.setBadgeMargin(380, 36);
                badgeViewNewVer.setBadgePosition(BadgeView.POSITION_TOP_LEFT);
                badgeViewNewVer.setPadding(15, 10, 15, 10);
                badgeViewNewVer.show();

            } else {
                badgeViewNewVer.hide();
            }
        }
    }

    private PermissionUtils.PermissionGrant mPermissionGrant = new PermissionUtils.PermissionGrant() {

        @Override
        public void onPermissionGranted(int requestCode) {
            switch (requestCode) {

                case PermissionUtils.CODE_READ_EXTERNAL_STORAGE:
                    Log.e("权限申请", "权限通过");
                    startActivity(new Intent(context, UploadApp.class));

                    break;
            }
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionUtils.requestPermissionsResult(getActivity(), requestCode, permissions, grantResults, mPermissionGrant);

    }
}
